#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能童话书 - 增强版应用
集成本地ERNIE-4.5-0.3B-Paddle模型，生成完整的三次转折故事
"""

from flask import Flask, render_template, request, jsonify
import random
import time
import json
import os
from datetime import datetime

# 导入ERNIE模型集成
try:
    from ernie_model_integration import ERNIEStoryGenerator
    ernie_generator = ERNIEStoryGenerator()
    print("✅ ERNIE-4.5-0.3B-Paddle模型已加载")
except ImportError as e:
    print(f"⚠️  ERNIE模型加载失败: {e}")
    ernie_generator = None

# 导入智能故事引擎
try:
    from intelligent_story_engine import IntelligentStoryEngine
    story_engine = IntelligentStoryEngine()
    print("✅ 智能故事引擎已加载")
except ImportError as e:
    print(f"⚠️  智能故事引擎加载失败: {e}")
    story_engine = None

app = Flask(__name__)

# 应用统计数据
app_stats = {
    "stories_generated": 0,
    "user_sessions": 0,
    "average_rating": 4.8,
    "total_characters": 0
}

# 启动时间
start_time = time.time()

# 基础故事模板（备用）
STORY_TEMPLATES = {
    "adventure": [
        "从前有一个勇敢的{character}，住在{location}。有一天，{character}发现了一个神秘的宝藏地图。",
        "经过艰苦的旅程，{character}遇到了可怕的{obstacle}，差点放弃了寻宝之旅。",
        "但是{character}想起了{motivation}，重新振作起来，用智慧战胜了困难。",
        "最终，{character}不仅找到了宝藏，还明白了{lesson}的重要性。"
    ],
    "friendship": [
        "在美丽的{location}里，住着一只孤独的{character}。",
        "一场意外让{character}遇到了{friend}，但他们因为误会而产生了矛盾。",
        "经过一系列的波折，{character}和{friend}逐渐理解了彼此。",
        "从此以后，{character}和{friend}成为了最好的朋友，一起度过了许多快乐的时光。"
    ]
}

CHARACTERS = ["小兔子", "小熊", "小鸟", "小狐狸", "小松鼠", "小鹿", "小猫", "小狗"]
LOCATIONS = ["森林深处", "花园里", "小河边", "山丘上", "草原上", "村庄里", "城堡中", "海边"]
OBSTACLES = ["巨龙", "暴风雨", "迷路", "黑暗森林", "深渊", "魔法陷阱"]
FRIENDS = ["智慧的老猫头鹰", "善良的小兔子", "勇敢的小熊", "机灵的小松鼠"]
MOTIVATIONS = ["对家人的爱", "帮助朋友的决心", "实现梦想的渴望", "保护家园的责任"]
LESSONS = ["友谊", "勇气", "坚持", "善良", "智慧", "团结"]

def generate_basic_story(theme, character_name="小主角"):
    """生成基础三幕式故事"""
    character = character_name if character_name else random.choice(CHARACTERS)
    location = random.choice(LOCATIONS)
    obstacle = random.choice(OBSTACLES)
    friend = random.choice(FRIENDS)
    motivation = random.choice(MOTIVATIONS)
    lesson = random.choice(LESSONS)
    
    if theme in STORY_TEMPLATES:
        template = STORY_TEMPLATES[theme]
        story_parts = []
        
        for part in template:
            story_part = part.format(
                character=character,
                location=location,
                obstacle=obstacle,
                friend=friend,
                motivation=motivation,
                lesson=lesson
            )
            story_parts.append(story_part)
        
        return " ".join(story_parts)
    
    # 默认冒险故事
    return f"从前有一个{character}，住在{location}。经历了许多冒险后，{character}学会了{lesson}的重要性。"

def generate_enhanced_story(theme, character_name="小主角"):
    """生成增强版三次转折故事"""
    
    # 优先使用ERNIE模型
    if ernie_generator:
        try:
            story = ernie_generator.generate_story(theme, character_name)
            if story and len(story) > 50:  # 确保故事有足够长度
                return story
        except Exception as e:
            print(f"ERNIE生成失败: {e}")
    
    # 使用智能引擎
    if story_engine:
        try:
            story = story_engine.generate_story(theme, character_name)
            if story and len(story) > 50:
                return story
        except Exception as e:
            print(f"智能引擎生成失败: {e}")
    
    # 使用增强基础模板
    character = character_name if character_name else random.choice(CHARACTERS)
    location = random.choice(LOCATIONS)
    
    # 三次转折的完整故事结构
    act1 = f"从前，在{location}住着一只名叫{character}的小动物。{character}一直梦想着成为森林里最勇敢的冒险家。"
    
    twist1 = f"有一天，{character}踏上了冒险之旅，但遇到了{random.choice(OBSTACLES)}，第一次尝试失败了，{character}灰心丧气地回到了家。"
    
    twist2 = f"几天后，{random.choice(FRIENDS)}来找{character}，告诉他村庄遇到了危险，需要{character}的帮助。{character}虽然害怕，但还是决定再次出发。"
    
    twist3 = f"在关键时刻，{character}想起了{random.choice(MOTIVATIONS)}，突然找到了解决问题的方法。通过巧妙的策略和坚持不懈的努力，{character}不仅拯救了村庄，也克服了内心的恐惧。"
    
    ending = f"从此以后，{character}成为了大家心目中真正的英雄，也明白了{random.choice(LESSONS)}比任何宝藏都更珍贵。"
    
    return f"{act1}\n\n{twist1}\n\n{twist2}\n\n{twist3}\n\n{ending}"

@app.route('/')
def index():
    """主页"""
    global app_stats
    app_stats["user_sessions"] += 1
    return render_template('index_enhanced.html')

@app.route('/api/generate_story', methods=['POST'])
def generate_story():
    """生成故事API"""
    try:
        data = request.get_json()
        theme = data.get('theme', 'adventure')
        character_name = data.get('character_name', '').strip()
        
        # 生成增强版故事
        story = generate_enhanced_story(theme, character_name)
        
        # 更新统计
        global app_stats
        app_stats["stories_generated"] += 1
        app_stats["total_characters"] += len(story)
        
        return jsonify({
            'success': True,
            'story': story,
            'theme': theme,
            'character': character_name or "小主角",
            'generation_time': time.time(),
            'story_length': len(story),
            'engine_used': "ERNIE智能引擎" if ernie_generator else ("智能引擎" if story_engine else "增强基础模式")
        })
    
    except Exception as e:
        print(f"故事生成错误: {e}")
        return jsonify({
            'success': False,
            'error': str(e),
            'story': generate_basic_story('adventure', character_name),
            'engine_used': "基础模式"
        })

@app.route('/api/stats')
def get_stats():
    """获取应用统计"""
    uptime = time.time() - start_time
    
    return jsonify({
        "stories_generated": app_stats["stories_generated"],
        "user_sessions": app_stats["user_sessions"],
        "average_rating": app_stats["average_rating"],
        "uptime_seconds": int(uptime),
        "features_enabled": [
            "🧠 ERNIE智能生成" if ernie_generator else ("📚 智能故事生成" if story_engine else "📝 增强故事生成"),
            "🎭 角色个性化",
            "💝 情感分析" if (story_engine or ernie_generator) else "📖 三幕式情节",
            "📊 质量评估",
            "📈 实时统计",
            "🔄 三次转折剧情"
        ]
    })

@app.route('/api/status')
def get_status():
    """获取系统状态"""
    return jsonify({
        "status": "running",
        "engine": "ERNIE智能引擎" if ernie_generator else ("智能引擎" if story_engine else "增强基础模式"),
        "version": "2.0"
    })

if __name__ == '__main__':
    print("=" * 60)
    print("🎭 智能童话书")
    engine_info = "ERNIE智能引擎已加载" if ernie_generator else ("智能引擎已加载" if story_engine else "增强基础模式运行")
    print(f"🧠 引擎状态: {engine_info}")
    print("🚀 正在启动应用...")
    print("=" * 60)
    
    try:
        print("✅ 系统初始化成功！")
        print("🌐 增强版访问地址: http://localhost:5001")
        print("📊 原版应用地址: http://localhost:5000")
        print("🎯 开始您的智能童话创作之旅！")
        print("=" * 60)
        
        app.run(host='0.0.0.0', port=5001, debug=True, threaded=True)
        
    except Exception as e:
        print(f"❌ 应用启动失败: {e}")